import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../widgets/tag_flow_widget.dart';
import '../providers/discover_category_provider.dart';
import '../utils/http_helper.dart';
import 'home/model/home_banner_model.dart';
import 'home/model/comic_category_item_model.dart';

class DiscoverPage extends StatefulWidget {
  const DiscoverPage({super.key});

  @override
  State<DiscoverPage> createState() => _DiscoverPageState();
}

class _DiscoverPageState extends State<DiscoverPage> {
  // Get category list from API
  List<String> _basicCategories =
      []; // Use categories returned directly from API
  Map<String, String> _categoryMap = {}; // Mapping from category name to ID
  bool _isLoading = true;
  bool _hasError = false;
  bool _isEmpty = false; // New: indicates empty data state

  // Add selection state management
  String _selectedStatus = 'All'; // Selected item for status filter
  String _selectedType = 'All'; // Selected item for type filter
  String _selectedCategory = ''; // Selected category

  // Comic list related states
  List<ComicItemModel> _comicList = [];
  bool _isLoadingComics = false;
  bool _hasComicError = false;
  bool _isLoadingMore = false; // Load more state
  bool _hasMore = true; // Whether there is more data
  int _currentPage = 1; // Current page number
  late ScrollController _scrollController; // Scroll controller

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
    _getCategoryData();
    _handleAppTrack();
  }

  Future<void> _handleAppTrack() async {
    await AppTrackingTransparency.requestTrackingAuthorization();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  // Listen to scroll events
  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      // Start loading more when 200 pixels from bottom
      _loadMore();
    }
  }

  // Get category data
  Future<void> _getCategoryData() async {
    try {
      setState(() {
        _isLoading = true;
        _hasError = false;
        _isEmpty = false; // Reset empty data state
      });

      final userResponse = await HttpUtil().getModel<List<HomeBannerModel>>(
        'Comic/GetComicCategoriesList',
        fromJson: (json) => (json as List)
            .map((item) => HomeBannerModel.fromJson(item))
            .toList(),
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        final banners = userResponse!.result!;
        // Filter data with type 0
        // final filteredBanners =
        //     banners.where((banner) => banner.type == 0).toList();
        final filteredBanners = banners;

        // If filteredBanners has no data, set empty data state
        if (filteredBanners.isEmpty) {
          setState(() {
            _isEmpty = true;
            _isLoading = false;
          });
          return;
        }
        // Extract category names and IDs
        final categoryNames = <String>[];
        final categoryMap = <String, String>{};

        for (final banner in filteredBanners) {
          final title = banner.title ?? 'Unknown';
          final id = banner.id ?? '';
          categoryNames.add(title);
          categoryMap[title] = id;
        }

        setState(() {
          // Use categories returned directly from API
          _basicCategories = categoryNames;
          _categoryMap = categoryMap;
          // Select first category by default
          if (categoryNames.isNotEmpty) {
            _selectedCategory = categoryNames.first;
          }
          _isLoading = false;
          _isEmpty = false;
        });

        // Load comic data after category data is loaded
        _loadComicData();
      } else {
        print("Failed to get categories");
        setState(() {
          _isLoading = false;
          _hasError = true;
        });
      }
    } catch (e) {
      print("Error getting categories: $e");
      setState(() {
        _isLoading = false;
        _hasError = true;
      });
    }
  }

  // Get comic list data
  Future<void> _loadComicData({bool isRefresh = false}) async {
    try {
      if (isRefresh) {
        setState(() {
          _currentPage = 1;
          _isLoadingComics = true;
          _hasComicError = false;
          _hasMore = true;
        });
      } else if (_currentPage == 1) {
        setState(() {
          _isLoadingComics = true;
          _hasComicError = false;
        });
      }

      // Get real categoryId
      final categoryId = _categoryMap[_selectedCategory] ?? '';

      // If no valid categoryId, don't make request
      if (categoryId.isEmpty) {
        print("Warning: categoryId is empty, skipping request");
        setState(() {
          _isLoadingComics = false;
          _comicList = [];
        });
        return;
      }

      // Build request parameters
      final params = <String, dynamic>{
        "categoryId": categoryId,
        "SortBy": 1, // Default sorting
        "PageSize": 18,
        "PageNo": isRefresh ? 1 : _currentPage,
      };

      // Add serialization status parameters
      if (_selectedStatus != 'All') {
        if (_selectedStatus == 'Ongoing') {
          params["OngoingStatus"] = 0; // Ongoing
        } else if (_selectedStatus == 'Completed') {
          params["OngoingStatus"] = 1; // Completed
        }
      }

      // Add charge status parameters
      if (_selectedType != 'All') {
        if (_selectedType == 'Free') {
          params["ChargeStatus"] = 0; // Free
        } else if (_selectedType == 'Paid') {
          params["ChargeStatus"] = 1; // User paid subscription content
        } else if (_selectedType == 'Vip') {
          params["ChargeStatus"] = 2; // VIP free
        }
      }

      final response = await HttpUtil().getModel<List<ComicItemModel>>(
        'Comic/GetComicList',
        params: params,
        fromJson: (json) => (json as List)
            .map((item) => ComicItemModel.fromJson(item))
            .toList(),
      );

      if (response?.status == 200 && response?.result != null) {
        final newComics = response!.result!;
        final hasMore = newComics.length >= 18;

        setState(() {
          if (isRefresh || _currentPage == 1) {
            _comicList = newComics;
          } else {
            _comicList.addAll(newComics);
            _isLoadingMore = false;
          }
          _isLoadingComics = false;
          _hasMore = hasMore;
          _currentPage = isRefresh ? 1 : _currentPage;
        });
      } else {
        print(
            "API returned error: status=${response?.status}, message=${response?.message}");
        setState(() {
          _isLoadingComics = false;
          _isLoadingMore = false;
          _hasComicError = true;
        });
      }
    } catch (e) {
      print("Error getting comic list: $e");
      setState(() {
        _isLoadingComics = false;
        _isLoadingMore = false;
        _hasComicError = true;
      });
    }
  }

  // Load more
  Future<void> _loadMore() async {
    if (_isLoadingMore || !_hasMore || _isLoadingComics) return;

    setState(() {
      _isLoadingMore = true;
      _currentPage = _currentPage + 1;
    });

    await _loadComicData();
  }

  // Pull to refresh
  Future<void> _refresh() async {
    await _loadComicData(isRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF211839),
        title: const Text(
          'Discover',
        ),
        titleSpacing: 16, // Remove default left margin
        centerTitle: false, // Ensure not centered
        // Add a search button
        // actions: [
        //   IconButton(
        //     icon: const Icon(
        //       Icons.search,
        //       color: Colors.white,
        //     ),
        //     onPressed: () {
        //       // Handle search button click event
        //       GoRouter.of(context).pushNamed('search');
        //     },
        //   ),
        // ],
      ),
      backgroundColor: const Color(0xFF211839),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
              ),
            )
          : _hasError
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.error_outline,
                        color: Colors.white54,
                        size: 48,
                      ),
                      const SizedBox(height: 16),
                      const Text(
                        // 英文
                        'Failed to load categories',
                        style: TextStyle(
                          color: Colors.white54,
                          fontSize: 16,
                        ),
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _getCategoryData,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF8A7CA8),
                        ),
                        child: const Text(
                          'Retry',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                )
              : _isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(
                            Icons.inbox_outlined,
                            color: Colors.white54,
                            size: 64,
                          ),
                          const SizedBox(height: 16),
                          const Text(
                            // 英文
                            'No categories available',
                            style: TextStyle(
                              color: Colors.white54,
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(height: 8),
                          const Text(
                            // 英文
                            'No categories available',
                            style: TextStyle(
                              color: Colors.white38,
                              fontSize: 14,
                            ),
                          ),
                          const SizedBox(height: 24),
                          ElevatedButton(
                            onPressed: _getCategoryData,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xFF8A7CA8),
                              padding: const EdgeInsets.symmetric(
                                horizontal: 24,
                                vertical: 12,
                              ),
                            ),
                            child: const Text(
                              // 英文
                              'Refresh',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ],
                      ),
                    )
                  : RefreshIndicator(
                      onRefresh: _refresh,
                      backgroundColor: const Color(0xFF2A1F3D),
                      color: const Color(0xFF8A7CA8),
                      child: CustomScrollView(
                        controller: _scrollController,
                        physics: const AlwaysScrollableScrollPhysics(),
                        slivers: [
                          // 分类标签区域
                          SliverToBoxAdapter(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 8),
                              child: TagFlowWidget(
                                items: _basicCategories,
                                maxRows: 2,
                                spaceHorizontal: 30,
                                selectedTextColor: Colors.pinkAccent,
                                unselectedTextColor: Colors.white70,
                                spaceVertical: 0,
                                itemHeight: 30,
                                itemStyle: const TextStyle(height: 1.1),
                                onSelectedChanged: (selectedItem) {
                                  if (selectedItem != null &&
                                      selectedItem != _selectedCategory) {
                                    setState(() {
                                      _selectedCategory = selectedItem;
                                      _currentPage = 1;
                                      _hasMore = true;
                                    });
                                    _loadComicData(isRefresh: true);
                                  }
                                },
                              ),
                            ),
                          ),

                          // 过滤选项区域
                          SliverToBoxAdapter(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 8),
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      _FilterChip(
                                        label: 'All',
                                        isSelected: _selectedStatus == 'All',
                                        onTap: () {
                                          setState(() {
                                            _selectedStatus = 'All';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                      _FilterChip(
                                        label: 'Ongoing',
                                        isSelected:
                                            _selectedStatus == 'Ongoing',
                                        onTap: () {
                                          setState(() {
                                            _selectedStatus = 'Ongoing';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                      _FilterChip(
                                        label: 'Completed',
                                        isSelected:
                                            _selectedStatus == 'Completed',
                                        onTap: () {
                                          setState(() {
                                            _selectedStatus = 'Completed';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 16),
                                  Row(
                                    children: [
                                      _FilterChip(
                                        label: 'All',
                                        isSelected: _selectedType == 'All',
                                        onTap: () {
                                          setState(() {
                                            _selectedType = 'All';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                      _FilterChip(
                                        label: 'Free',
                                        isSelected: _selectedType == 'Free',
                                        onTap: () {
                                          setState(() {
                                            _selectedType = 'Free';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                      _FilterChip(
                                        label: 'Paid',
                                        isSelected: _selectedType == 'Paid',
                                        onTap: () {
                                          setState(() {
                                            _selectedType = 'Paid';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                      _FilterChip(
                                        label: 'Vip',
                                        isSelected: _selectedType == 'Vip',
                                        onTap: () {
                                          setState(() {
                                            _selectedType = 'Vip';
                                            _currentPage = 1;
                                            _hasMore = true;
                                          });
                                          _loadComicData(isRefresh: true);
                                        },
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),

                          // 主内容网格列表或加载状态
                          _isLoadingComics && _comicList.isEmpty
                              ? const SliverFillRemaining(
                                  child: Center(
                                    child: CircularProgressIndicator(
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                          Color(0xFF8A7CA8)),
                                    ),
                                  ),
                                )
                              : _comicList.isEmpty
                                  ? const SliverFillRemaining(
                                      child: Center(
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            const Icon(
                                              Icons.hourglass_empty,
                                              color: Colors.white54,
                                              size: 48,
                                            ),
                                            const SizedBox(height: 16),
                                            const Text(
                                              'No comics',
                                              style: TextStyle(
                                                color: Colors.white54,
                                                fontSize: 16,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    )
                                  : SliverPadding(
                                      padding: const EdgeInsets.all(12),
                                      sliver: SliverGrid(
                                        gridDelegate:
                                            const SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 3,
                                          childAspectRatio: 0.7,
                                          crossAxisSpacing: 12,
                                          mainAxisSpacing: 12,
                                        ),
                                        delegate: SliverChildBuilderDelegate(
                                          (context, index) {
                                            // 显示漫画项
                                            if (index < _comicList.length) {
                                              return HengItemWidgt(
                                                  comic: _comicList[index]);
                                            }

                                            // 显示加载更多指示器（只在第一个位置显示，其他位置为空）
                                            if (index == _comicList.length) {
                                              return _buildLoadMoreIndicator();
                                            }

                                            // 其他位置返回空容器
                                            return const SizedBox.shrink();
                                          },
                                          childCount: _comicList.length +
                                              (_hasMore || _isLoadingMore
                                                  ? 3
                                                  : 0),
                                        ),
                                      ),
                                    ),
                        ],
                      ),
                    ),
    );
  }

  // 构建加载更多指示器
  Widget _buildLoadMoreIndicator() {
    if (_isLoadingMore) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
            strokeWidth: 2.0,
          ),
        ),
      );
    } else if (!_hasMore) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Text(
            'No more content',
            style: TextStyle(
              color: Colors.white54,
              fontSize: 12,
            ),
          ),
        ),
      );
    }
    return const SizedBox.shrink();
  }
}

class HengItemWidgt extends StatelessWidget {
  final ComicItemModel? comic;

  const HengItemWidgt({super.key, this.comic});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => {
        if (comic?.id != null)
          {
            GoRouter.of(context).pushNamed(
              'direct_reader',
              pathParameters: {
                'chapterId': comic?.id ?? "",
                'comicId': comic?.id ?? "",
              },
            )
          }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: CachedNetworkImage(
                imageUrl: comic?.cover ?? "",
                fit: BoxFit.cover,
                width: double.infinity,
                placeholder: (context, url) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Center(
                    child: CircularProgressIndicator(
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Color(0xFF8A7CA8)),
                      strokeWidth: 2.0,
                    ),
                  ),
                ),
                errorWidget: (context, url, error) => Container(
                  color: const Color(0xFF2A1F3D),
                  child: const Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.broken_image,
                          color: Color(0xFF8A7CA8), size: 24),
                      SizedBox(height: 4),
                      Text(
                        'Load Failed',
                        style: TextStyle(
                          color: Color(0xFF8A7CA8),
                          fontSize: 10,
                        ),
                      ),
                    ],
                  ),
                ),
                fadeInDuration: const Duration(milliseconds: 300),
                fadeOutDuration: const Duration(milliseconds: 100),
              ),
            ),
          ),
          const SizedBox(height: 8),
          Text(
            comic?.title ?? "Loading...",
            style: const TextStyle(
              fontSize: 11,
              fontWeight: FontWeight.w500,
              color: Color(0xFFB8B3C7),
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

// 过滤选项组件
class _FilterChip extends StatelessWidget {
  final String label;
  final bool isSelected;
  final VoidCallback onTap;

  const _FilterChip({
    required this.label,
    required this.isSelected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(right: 16),
      child: GestureDetector(
        onTap: onTap,
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.pinkAccent : Colors.grey[600],
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }
}
